// pages/order/order.js
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userID: "",
    userName: "",
    showText: "",
    commentText: "",
    currentOrderId: "",
    isCommentDialogShow: false,
    orderList: [],
  },

  showCommentDialog(e) {
    const orderId = e.currentTarget.dataset.orderId;
    this.setData({
        isCommentDialogShow: true,
        currentOrderId: orderId
    });
  },

  hideCommentDialog() {
      this.setData({
          isCommentDialogShow: false,
          commentText: ''
      });
  },

  // 监听评论输入
  onCommentInput(e) {
    this.setData({
        commentText: e.detail.value
    });
  },

  submitComment(e) {
    const orderId = e.currentTarget.dataset.orderId;
    const commentText = this.data.commentText;

    if (commentText.length > 0) {
        console.log(`Submitting comment for order ${orderId}:`, commentText);

        const registerData = {
          commentId: orderId,
          commentUser: app.globalData.userID,
          commentContent: commentText
        };
        wx.request({
          url: 'http://localhost:9090/comment/addComment',
          method: 'POST',
          data: registerData,
          header: {
            'Content-Type': 'application/json'
          },
          success(res) {
            console.log(res.data)
            if(res.data.code == "200") {
              wx.showToast({
                title: '评论成功',
                icon: 'success',
              });
            }
          },
        });
        this.hideCommentDialog();
    } else {
        wx.showToast({
            title: '评论不能为空',
            icon: 'none'
        });
    }
  },

  jumpLogin: function() {
    if(!this.data.userName) {
      wx.navigateTo({
        url: '../login/login',
      })
    }
  },

  judgeHaveUser: function() {
    if (!this.data.userID) {
      this.setData({
        showText: "请先登录/注册账号"
      });
    } else {
      this.setData({
        showText: "暂无其他订单信息",
      });
      this.getOrderList();
    }
    // console.log(this.data.showText);
  },

  processOrders: function(data) {
    const orderList = [];
    const foodMap = {};
    data.forEach(item => {
        if (item.foodID) {
            foodMap[item.foodID] = item;
        }
    });
    data.forEach(item => {
        if (item.orderId) {
            const foodInfo = foodMap[item.orderFood];
            if (foodInfo) {
                orderList.push({
                    orderId: item.orderId,
                    orderUser: item.orderUser,
                    orderDate: item.orderDate,
                    orderFood: item.orderFood,
                    orderState: item.orderState,
                    foodName: foodInfo.foodName,
                    foodImage: foodInfo.foodImage,
                    foodType: foodInfo.foodType,
                    foodNum: foodInfo.foodNum,
                    foodPrice: foodInfo.foodPrice
                });
            }
        }
    });
    return orderList;
  },

  getOrderList: function(e) {
    const orderData = { orderUser: this.data.userID };
    wx.request({
      url: 'http://localhost:9090/order/queryOrder',
      method: 'POST',
      data: orderData,
      header: {
        'Content-Type': 'application/json'
      },
      success:(res) => {
        const orderList = this.processOrders(res.data.data);
        // console.log(orderList);
        if(res.data.code == "200") {
          this.setData({
            orderList: orderList
          })
        }
      }
    })
  },

  refundOrder: function(orderId) {
    const refundData = {
      orderId: orderId,
      orderState: "退款成功"
    }
    // console.log(refundData)
    wx.request({
      url: 'http://localhost:9090/order/updateOrderState',
      method: 'POST',
      data: refundData,
      header: {
        'Content-Type': 'application/json'
      },
      success:(res) => {
        if(res.data.code === "200") {
          wx.showToast({
            icon: 'success',
            title: '退款成功',
          })
          this.getOrderList();
        }
      }
    })
  },

  refundFood: function(e) {
    const orderId = e.currentTarget.dataset.orderId;
    wx.showModal({
      title: '模拟退款',
      content: '确定要退款此菜品吗？',
      showCancel: true,  
      cancelText: '取消', 
      confirmText: '确定',
      success:(res) => {
          if (res.confirm) {
            this.refundOrder(orderId)
          } else if (res.cancel) {
            console.log('用户点击了“取消”按钮');
          }
      }
    });
  },

  deleteOrderItem: function(orderId) {
    const deleteData = { orderId: orderId }
    wx.request({
      url: 'http://localhost:9090/order/deleteOrder',
      method: 'POST',
      data: deleteData,
      header: {
        'Content-Type': 'application/json'
      },
      success:(res) => {
        if(res.data.code === "200") {
          wx.showToast({
            icon: 'success',
            title: '删除成功',
          })
          this.getOrderList();
        }
      }
    })
  },

  deleteOrder: function(e) {
    const orderId = e.currentTarget.dataset.orderId;
    wx.showModal({
      title: '模拟删除',
      content: '确定要删除此记录吗？',
      showCancel: true,  
      cancelText: '取消', 
      confirmText: '确定',
      success:(res) => {
          if (res.confirm) {
            this.deleteOrderItem(orderId)
          } else if (res.cancel) {
            console.log('用户点击了“取消”按钮');
          }
      }
    });
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      userID: app.globalData.userID,
      userName: app.globalData.userName
    });
    this.judgeHaveUser();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      userID: app.globalData.userID,
      userName: app.globalData.userName
    });
    this.judgeHaveUser();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})